package com.zxl.openapi.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zxl.openapi.constans.SystemParameter;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Component
public class TimeStampFilter extends ZuulFilter {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {

        Map<String, Map<Object, Object>> allApiInfoMap = SystemParameter.allApiInfoMap;

        RequestContext context = RequestContext.getCurrentContext();

        HttpServletRequest request = context.getRequest();

        String method = request.getParameter("method");
        //获取当前接口的map
        Map<Object, Object> map = allApiInfoMap.get(SystemParameter.REDIS_APIPRE + method);
        //获取当前过滤器需要经过的filters
        String filters = (String) map.get("filters");
        return context.sendZuulResponse() && filters != null && filters.contains(getClass().getName());
    }

    @Override
    public Object run() throws ZuulException {
        //获取用户传递的时间
        RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();

        String timestamp = request.getParameter("timestamp");

        try {
            Date date = simpleDateFormat.parse(timestamp);
            System.out.println(date);
            //获取服务器现在的时间
            Date currentDate = new Date();
            //两者的毫秒值不超过我们的阈值
            //时间差
            long subTime = currentDate.getTime() - date.getTime();
            System.out.println(currentDate);
            System.out.println(subTime);
            //小于0代表来自于未来,大于60000代表来自于过去超过一分钟了都不符合我们的要求
            if(subTime < 0 || subTime > 60000){

                currentContext.setSendZuulResponse(false);

                currentContext.getResponse().setContentType("text/html;charset=utf-8");

                currentContext.setResponseBody("时间超出范围");

            }
        } catch (ParseException e) {

            e.printStackTrace();

            currentContext.setSendZuulResponse(false);

            currentContext.getResponse().setContentType("text/html;charset=utf-8");

            currentContext.setResponseBody("时间格式不正确");

        }
        return null;
    }
}
